package app.geobeans.cn.sockettest;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private MessageService mService;
    private ServiceConnection conn;
    private Button mBtnSync;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Log.i(TAG,"onCreate");
        initService();

        mBtnSync = (Button) findViewById(R.id.btn_sync);
        mBtnSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG,"setOnClickListener, 同步时间呀");
                mService.sendMessage("{\"Command\":\"GETTIME\"}", "");
            }
        });

    }

    private void initService() {
        Intent itt = new Intent(this,MessageService.class);
        startService(itt);
       conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                MessageService.MessageServiceBinder binder = (MessageService.MessageServiceBinder) iBinder;
                mService = binder.getService();
                Log.i(TAG,"绑定服务成功");
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        } ;
        Log.i(TAG,"bind service : " + bindService(itt,conn,BIND_AUTO_CREATE));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        Intent itt = new Intent(this,MessageService.class);
        stopService(itt);
    }
}
